from app.core.logger import logger
from app.services.xm_service import (
    create_order,
)
from app.crud.uc.partner_token import get_partner_token
from app.core.task_db import TaskDBSession
from app.core.constants import ThirdPartner
from app.models.xm.monitor_buy import MonitorBuy
from app.schemas.xm.xm_buy_order import XMBuyOrderCreate
from app.crud.xm.xm_buy_order import create_xm_buy_order
from app.crud.xm.monitor_buy import update_buy_count, update_monitor_buy_pause, get_monitor_buy
from app.core.utils import yuan_str_to_cents
from app.core.constants import MonitorBuyStatus
async def buy_archive(
    uid: int,
    goodsId: str,
    goodsPrice: str,
    monitorBuyId: int,
):
    """
    购买XM藏品
    """
    logger.info(f"开始购买藏品 uid={uid}, goodsId={goodsId}, goodsPrice={goodsPrice}")
    # 从数据库中查询用户XM Token
    async with TaskDBSession() as db_session:
        partner_token = await get_partner_token(
            session=db_session,
            uid=uid,
            partner=ThirdPartner.XMeta,
        )
        if not partner_token:
            logger.error(f"用户 {uid} 未绑定XM Token")
            return
        # 创建订单，购买藏品
        order_resp = await create_order(
            xm_auth=f"Bearer {partner_token.accessToken}",
            goodsId=goodsId,
            goodsPrice=goodsPrice,
        )
        logger.info(f"create_order响应: {order_resp}")
        # if order_resp["code"] != 200:
        #     logger.error(f"create_order失败: {order_resp}")
        #     return None
        
        # 查询监控挂单记录
        monitorBuy = await get_monitor_buy(
            session=db_session,
            monitor_buy_id=monitorBuyId,
        )
        if not monitorBuy:
            logger.error(f"监控挂单记录 {monitorBuyId} 不存在")
            return

        # 构建购买订单模型
        xm_buy_order = XMBuyOrderCreate(
            uid=uid,
            monitorBuyId=monitorBuy.id,
            orderId=order_resp["data"]["orderId"] if order_resp["code"] == 200 else 0,
            orderNo=order_resp["data"]["orderNo"] if order_resp["code"] == 200 else "",
            goodsId=int(goodsId),
            goodsPrice=yuan_str_to_cents(goodsPrice),
            archiveId=monitorBuy.archiveId,
            archiveName=monitorBuy.archiveName,
            archiveImg=monitorBuy.archiveImg,
            platformId=monitorBuy.platformId,
            status=order_resp["code"] == 200 and 0 or 1,
            failMsg=order_resp["msg"],
        )

        # 保存购买订单
        await create_xm_buy_order(
            session=db_session,
            xm_buy_order=xm_buy_order,
        )
        # 仅当订单状态为成功时，更新监控购买的已购买数量
        if xm_buy_order.status == 0:
            await update_buy_count(
                session=db_session,
                monitor_buy=monitorBuy,
                buy_count=1,
            )
        else:
            # 更新监控购买的状态为暂停
            await update_monitor_buy_pause(
                session=db_session,
                monitor_buy=monitorBuy,
                status=MonitorBuyStatus.PAUSED,
                pauseRemark=xm_buy_order.failMsg,
            )
